# TODO: 导入必要的库和模块
import time
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import pickle
from tqdm import tqdm
from sklearn.neighbors import KNeighborsClassifier

# TODO: 加载数字数据集
digits = load_digits()

# TODO: 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(digits.data,
        digits.target, test_size=0.2, random_state=42)

# print(digits.data.shape)

# TODO: 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_accuracy = 0
best_k = 0
best_knn_model = None

# TODO: 初始化一个列表以存储每个k值的准确率
accuracies = []

# TODO: 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
# 使用tqdm创建进度条
with tqdm(total=40, desc="Training KNN models") as pbar:
    # 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
    for k in range(1, 41):
        knn_model = KNeighborsClassifier(n_neighbors=k)
        knn_model.fit(X_train, y_train)
        accuracy = knn_model.score(X_test, y_test)
        accuracies.append(accuracy)
        if accuracy > best_accuracy:
            best_accuracy = accuracy
            best_k = k
            best_knn_model = knn_model
        time.sleep(0.1)
        pbar.update(1)  # 更新进度条

# TODO: 将最佳KNN模型保存到二进制文件
with open('best_knn_model.pkl', 'wb') as f:
    pickle.dump(best_knn_model, f)

# TODO: 打印最佳准确率和相应的k值
print(f'Best accuracy: {best_accuracy:.2f} with k={best_k}')


# 绘制折线图
plt.figure(figsize=(10, 6))
plt.plot(range(1, 41), accuracies, marker='o', linestyle='-', color='b', label='Accuracy')
plt.axvline(x=best_k, color='r', linestyle='--', label='Best k')
plt.text(best_k, best_accuracy, f'Best k={best_k}, Accuracy={best_accuracy:.2f}', color='red')

# 设置图表标题和坐标轴标签
plt.title('KNN Accuracy for Different k Values')
plt.xlabel('k Value')
plt.ylabel('Accuracy')

# 添加图例
plt.legend()

# 保存图表为PDF
plt.savefig('knn_accuracy.pdf')

# 显示图表
plt.show()
